package com.game.chat_room;

import com.game.tools.LogTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@PropertySource(value = {
        "classpath:chatroom.properties",
}, encoding = "utf-8")
@Component
public class ServerListener extends Thread{
    @Value("${chat-server-port}")
    private int server_port;

    public ServerListener() {
    }

    // 服务是否开启
    private boolean running = false;

    public void setRunning(boolean running){
        this.running = running;
    }

    public boolean isRunning(){
        return this.running;
    }

    public void run()
    {
        try {
            /**
             * 开启socket服务
             */
            ServerSocket serversocket= new ServerSocket(this.server_port);
            System.out.println("聊天服务已启动，端口：" + this.server_port);
            while(true) {
                Socket socket=serversocket.accept();  //进程会阻塞在这句，直到有socket连接进来，就往下执行
                System.out.println("新的客户端已连接");
                ChatThread cs=new ChatThread(socket);
                cs.start();
                LogTool.outputLog("线程已启动：" + cs.toString());
                ChatThreadManager.getChartManager().add(cs);
                LogTool.outputLog("线程已加入线程管理器");
                LogTool.outputLog("当前管理器中线程(" + ChatThreadManager.ChatSocket_vector.size() + ")：" + ChatThreadManager.seeChatSocket_vector());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
